package com.example.onlinemallsystem.controller;

import com.example.onlinemallsystem.entity.Product;
import com.example.onlinemallsystem.service.CategoryService;
import com.example.onlinemallsystem.service.ProductService;
import com.example.onlinemallsystem.service.UserService;
import com.example.onlinemallsystem.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;

@RestController
@RequestMapping("/Products")
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private UserService userService;

    // 逻辑删除商品 - 验证卖家权限
    // 物理删除商品 - 验证卖家权限
    @DeleteMapping("/{id}")
    public JsonResult<Void> deleteProduct(@PathVariable Long id, HttpSession session) {
        // 获取当前登录用户ID
        Long sellerId = (Long) session.getAttribute("userId");
        if (sellerId == null) {
            return new JsonResult<>(401, "用户未登录");
        }

        // 验证商品是否存在
        Product product = productService.selectProductById(id);
        if (product == null) {
            return new JsonResult<>(404, "商品不存在");
        }

        // 验证商品是否属于当前卖家
        if (!product.getSellerId().equals(sellerId)) {
            return new JsonResult<>(403, "无权限删除此商品");
        }

        int result = productService.deleteProduct(id);
        if (result > 0) {
            return new JsonResult<>(200, "删除成功");
        }
        return new JsonResult<>(400, "删除失败");
    }

    // 更新商品信息 - 验证卖家权限
    @PutMapping("/{id}")
    public JsonResult<Product> updateProduct(@PathVariable Long id, @RequestBody Product product, HttpSession session) {
        Long sellerId = (Long) session.getAttribute("userId");
        if (sellerId == null) {
            return new JsonResult<>(401, "用户未登录");
        }
        Product existingProduct = productService.selectProductById(id);
        if (existingProduct == null) {
            return new JsonResult<>(404, "商品不存在");
        }
        product.setId(id);
        product.setSellerId(sellerId);

        // 重新赋值分类名和卖家名
        String categoryName = categoryService.getCategoryById(product.getCategoryId()).getName();
        product.setCategoryName(categoryName);
        String sellerName = userService.getById(sellerId).getUsername();
        product.setSellerName(sellerName);

        int result = productService.updateProduct(product);
        if (result > 0) {
            return new JsonResult<>(200, "更改成功");
        }
        return new JsonResult<>(400, "更改失败");
    }

    @GetMapping("/{id}")
    public JsonResult<Product> getProductById(@PathVariable Long id) {
        Product product = productService.selectProductById(id);
        System.out.println("后端查到的 sellerName: " + (product != null ? product.getSellerName() : "null"));
        if (product != null) {
            return new JsonResult<>(200, product);
        }
        return new JsonResult<>(400, "查找失败，该商品不存在");
    }

    // 查询所有商品 - 公开接口，所有用户都可以查看
    @GetMapping
    public JsonResult<List<Product>> listAllProducts() {
        List<Product> productList = productService.selectAllProducts();
        return new JsonResult<>(200, productList);
    }

    // 获取当前卖家的所有商品
    @GetMapping("/seller")
    public JsonResult<List<Product>> getSellerProducts(HttpSession session) {
        // 获取当前登录用户ID
        Long sellerId = (Long) session.getAttribute("userId");
        if (sellerId == null) {
            return new JsonResult<>(401, "用户未登录");
        }
        System.out.println("当前session userId: " + sellerId);
        List<Product> productList = productService.selectProductsBySellerId(sellerId);

        return new JsonResult<>(200, productList);
    }

    // 按分类 ID 查询商品 - 公开接口
    @GetMapping("/category/{categoryId}")
    public JsonResult<List<Product>> listProductsByCategoryId(@PathVariable Long categoryId) {
        List<Product> productList = productService.selectProductsByCategoryId(categoryId);
        return new JsonResult<>(200, "找到" + productList.size() + "个商品", productList);
    }

    // 商品名称模糊查询 - 公开接口
    @GetMapping("/search")
    public JsonResult<List<Product>> searchProductsByName(@RequestParam String name) {
        List<Product> productList = productService.selectProductsByName(name);
        return new JsonResult<>(200, productList);
    }

    // 搜索当前卖家的商品
    @GetMapping("/seller/search")
    public JsonResult<List<Product>> searchSellerProducts(@RequestParam String name, HttpSession session) {
        // 获取当前登录用户ID
        Long sellerId = (Long) session.getAttribute("userId");
        if (sellerId == null) {
            return new JsonResult<>(401, "用户未登录");
        }

        List<Product> productList = productService.selectSellerProductsByName(sellerId, name);
        return new JsonResult<>(200, productList);
    }

    // 增加商品销量 - 公开接口
    @PutMapping("/{id}/sales")
    public JsonResult<Void> increaseProductSales(
            @PathVariable Long id,
            @RequestParam Integer amount) {
        int result = productService.increaseProductSales(id, amount);
        if (result > 0) {
            return new JsonResult<>(200, "增加成功");
        }
        return new JsonResult<>(400, "添加失败,库存不足");
    }

    // 通用图片上传接口（用于添加商品时）
    @PostMapping("/upload/image")
    public JsonResult<String> uploadImage(@RequestParam("file") MultipartFile file, HttpSession session) {
        Long sellerId = (Long) session.getAttribute("userId");
        if (sellerId == null) {
            return new JsonResult<>(401, "用户未登录");
        }

        try {
            // 1. 保存图片到服务器
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            String uploadDir = "D:/upload/"; // 确保此目录存在

            // 创建目录（如果不存在）
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            File dest = new File(uploadDir + fileName);
            file.transferTo(dest);

            // 2. 返回图片访问路径
            String imageUrl = "/upload/" + fileName;
            return new JsonResult<>(200, "上传成功", imageUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult<>(500, "上传失败：" + e.getMessage());
        }
    }

    // 为特定商品上传图片接口
    @PostMapping("/{productId}/upload/image")
    public JsonResult<String> uploadProductImage(@PathVariable Long productId,
                                                 @RequestParam("file") MultipartFile file,
                                                 HttpSession session) {
        Long sellerId = (Long) session.getAttribute("userId");
        if (sellerId == null) {
            return new JsonResult<>(401, "用户未登录");
        }

        // 验证商品是否属于当前卖家
        Product product = productService.selectProductById(productId);
        if (product == null) {
            return new JsonResult<>(404, "商品不存在");
        }
        if (!product.getSellerId().equals(sellerId)) {
            return new JsonResult<>(403, "无权限操作此商品");
        }

        try {
            // 1. 保存图片到服务器
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            String uploadDir = "D:/upload/";

            // 创建目录（如果不存在）
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            File dest = new File(uploadDir + fileName);
            file.transferTo(dest);

            // 2. 更新商品图片路径
            String imageUrl = "/upload/" + fileName;
            product.setImages(imageUrl);
            productService.updateProduct(product);

            return new JsonResult<>(200, "图片上传成功", imageUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult<>(500, "上传失败：" + e.getMessage());
        }
    }

    // 添加商品接口，支持图片上传
    @PostMapping("add")
    public JsonResult<Product> createProduct(@RequestBody Product product, HttpSession session) {
        Long sellerId = (Long) session.getAttribute("userId");
        if (sellerId == null) {
            return new JsonResult<>(401, "用户未登录");
        }
        product.setSellerId(sellerId);

        // 1. 查询分类名称
        String categoryName = categoryService.getCategoryById(product.getCategoryId()).getName();
        product.setCategoryName(categoryName);

        // 2. 查询卖家名称
        String sellerName = userService.getById(sellerId).getUsername();
        product.setSellerName(sellerName);

        if (productService.existsByName(product.getName())) {
            return new JsonResult<>(400, "商品名称已存在，请使用其他名称");
        }

        // 3. 插入商品
        productService.insertProduct(product);

        // 4. 返回包含ID的商品信息
        return new JsonResult<>(200, "新增商品成功", product);
    }

    // 更新商品库存 - 验证卖家权限
    @PutMapping("/{id}/stock")
    public JsonResult<Void> updateProductStock(@PathVariable Long id,
                                               @RequestParam Integer stock,
                                               HttpSession session) {
        // 获取当前登录用户ID
        Long sellerId = (Long) session.getAttribute("userId");
        Product product = productService.selectProductById(id);
        System.out.println("当前session userId: " + sellerId);
        System.out.println("商品sellerId: " + (product != null ? product.getSellerId() : "null"));
        if (sellerId == null) {
            return new JsonResult<>(401, "用户未登录");
        }

        // 验证商品是否属于当前卖家
        if (product == null) {
            return new JsonResult<>(404, "商品不存在");
        }

        int result = productService.updateProductStock(id, stock);
        if (result > 0) {
            return new JsonResult<>(200, "库存更新成功");
        }
        return new JsonResult<>(400, "库存更新失败");
    }

    // 更新商品价格 - 验证卖家权限
    @PutMapping("/{id}/price")
    public JsonResult<Void> updateProductPrice(@PathVariable Long id,
                                               @RequestParam Double price,
                                               HttpSession session) {
        // 获取当前登录用户ID
        Long sellerId = (Long) session.getAttribute("userId");
        Product product = productService.selectProductById(id);
        System.out.println("当前session userId: " + sellerId);
        System.out.println("商品sellerId: " + (product != null ? product.getSellerId() : "null"));
        if (sellerId == null) {
            return new JsonResult<>(401, "用户未登录");
        }

        // 验证商品是否属于当前卖家
        if (product == null) {
            return new JsonResult<>(404, "商品不存在");
        }

        int result = productService.updateProductPrice(id, price);
        if (result > 0) {
            return new JsonResult<>(200, "价格更新成功");
        }
        return new JsonResult<>(400, "价格更新失败");
    }
}